package com.hup.minicontroller.common.bluetooth.handler;

import android.os.Handler;
import android.util.Log;

import com.hup.minicontroller.common.bluetooth.framework.BtBaseFunctionHandler;
import com.hup.minicontroller.common.bluetooth.framework.BtChannel;
import com.hup.minicontroller.common.bluetooth.model.BaseBtDataPacket;
import com.hup.minicontroller.common.bluetooth.model.BtLoginRequestPacket;
import com.hup.minicontroller.common.bluetooth.model.BtLoginResponsePacket;

import java.io.IOException;
import java.util.Iterator;

/**
 * 客户端的登陆认证处理器
 *
 * @author hugan
 * @date 2021/5/18
 */
public class BtLoginResponseHandler implements BtBaseFunctionHandler {
    private static final String TAG = BtLoginResponseHandler.class.getSimpleName();

    private BtLoginResponseCallback loginResponseCallback;

    @SuppressWarnings("unchecked")
    public BtLoginResponseHandler(BtLoginResponseCallback loginResponseCallback) {
        this.loginResponseCallback = loginResponseCallback;
        BtDataSplitCodecHandler.INSTANCE.registerType(loginResponseCallback.getLoginResponseType());
    }

    @Override
    public void onChannelActive(BtChannel btChannel) {
        BtLoginRequestPacket loginValidData = loginResponseCallback.getLoginValidData();
        btChannel.send(loginValidData);
        loginResponseCallback.getHandler().postDelayed(() -> {
            BtLoginResponsePacket loginResponse = btChannel.getLoginResponse();
            if (loginResponse == null) {
                Log.w(TAG, "channelActive: 服务端无回复认证请求,主动断开连接:" + btChannel.getRemoteDevice().getName());
                btChannel.onLoginValidResult(false, null, BtLoginResponsePacket.failure("服务端无回复认证请求"));
                btChannel.disconnect();
            }
        }, loginResponseCallback.getLoginTimeout());
    }

    @Override
    public BaseBtDataPacket onReceived(BtChannel btChannel, BaseBtDataPacket data, Iterator<BtBaseFunctionHandler> it) throws IOException {
        it.remove();//不论结果,都移除本处理器
        if (!(data instanceof BtLoginResponsePacket)) {
            Log.w(TAG, "onReceived: 登陆认证回复数据异常=" + data);
            btChannel.onLoginValidResult(false, null, BtLoginResponsePacket.failure("服务端无回复认证请求"));
            btChannel.disconnect();
            return null;
        }
        BtLoginResponsePacket loginResponse = (BtLoginResponsePacket) data;
        btChannel.onLoginValidResult(loginResponse.isSuccess(), null, loginResponse);
        if (!loginResponse.isSuccess()) btChannel.disconnect();
        return null;
    }

    public interface BtLoginResponseCallback<T extends BtLoginRequestPacket, R extends BtLoginResponsePacket> {

        /**
         * 发送登陆认证请求后,n毫秒内没收到服务端的回复,则主动断开连接;
         * 有登陆认证时业务时才使用
         */
        default int getLoginTimeout() {
            return 1000;
        }

        /**
         * 子线程handler:用于处理socket连接后,超时未认证功能
         */
        Handler getHandler();

        Class<R> getLoginResponseType();

        T getLoginValidData();
    }

}
